from selenium import webdriver
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.service import Service
import time
import os
import urllib.request
class Weather_Getter:
    def download_image(self):
        f_path = 'D://NMC5_figure'
        gecko_driver_path = "C:\\Users\\Cold'Rain\\Desktop\\geckodriver-v0.33.0-win64\\geckodriver.exe"
        # 固定搭配直接用就行了
        fire_driver = webdriver.Firefox(executable_path=gecko_driver_path)
        fire_driver.get('http://www.nmc.cn/publish/radar/chinaall.html')
        scal_index = fire_driver.find_element_by_id('zoomin')
        time.sleep(1)
        click_action = ActionChains(fire_driver).move_to_element(scal_index)
        click_action.click(scal_index).perform()

        try:
            time.sleep(3)
            image_index = fire_driver.find_element_by_xpath('//*[@id="IV_viewer"]/img')
            image_src = str(image_index.get_attribute('src'))
            image_save = image_src.split('/')[-1].split('?')[0]
            time_index = fire_driver.find_element_by_xpath('//*[@id="beginTime"]')
            acc_time = str(time_index.text).split(' ')[-1][:-1]
            if os.path.exists(f_path) is not True:
                os.makedirs(f_path)
            f_acc_time = '_' + acc_time.split('/')[0].replace(':', '_')
            final_path = f_path + '/' + str(image_save)[-21:-13] + f_acc_time + '.png'
            if str(image_save)[-21:-13] + f_acc_time + '.png' in os.listdir(f_path):
                pass
            else:
                urllib.request.urlretrieve(image_src, final_path)
                print('{}打印完成'.format(final_path))
            time.sleep(3)
            prev_index = fire_driver.find_element_by_xpath('//*[@id="IV_nextBtn"]')
            click_action_2 = ActionChains(fire_driver).move_to_element(prev_index)
            click_action_2.click(prev_index).perform()
            time.sleep(3)
            fire_driver.quit()
        except:
            try:
                fire_driver.refresh()
                time.sleep(10)
                scal_index = fire_driver.find_element_by_id('zoomin')
                click_action = ActionChains(fire_driver).move_to_element(scal_index)
                click_action.click(scal_index).perform()
                fire_driver.quit()
            except:
                fire_driver.back()
                scal_index = fire_driver.find_element_by_id('zoomin')
                click_action = ActionChains(fire_driver).move_to_element(scal_index)
                click_action.click(scal_index).perform()
                fire_driver.quit()

a = Weather_Getter()
a.download_image()